<template>
  <modal-form
    :form-state="formState"
    :show="show"
    title="在线导出"
    width="600px"
    :rules="modelFormRules"
    :loading="loading"
    :body-style="{ padding: '24px 0' }"
    @cancel="onCancel"
    @ok="onOk"
  >
    <template #default="{ formState }" v-if="show">
      <div class="from-content my-scrollbar">
        <a-form-item name="modelBaseId">
          <radio-tree-data ref="mainModuleRef" v-model:value="formState.modelBaseId" type="model" @update:value="onRadioTreeChange" />
        </a-form-item>
        <div class="item-to-inline">
          <a-form-item required label="版本号">
            <div class="fbc">
              <a-form-item name="versionId">
                <a-select
                  v-model:value="formState.versionId"
                  :disabled="!formState.modelBaseId"
                  style="width: 252px"
                  placeholder="请选择版本号"
                  :field-names="{ label: 'version', value: 'id' }"
                  :options="versionOption"
                  :get-popup-container="(triggerNode: any) => triggerNode.parentNode"
                />
              </a-form-item>
              <a-form-item v-if="formState.versionId === 'add-version'" name="versionInput">
                <a-input v-model:value="formState.versionInput" v-trim :maxlength="10" placeholder="例如：1.0.1" style="width: 252px" />
              </a-form-item>
            </div>
          </a-form-item>
        </div>
        <a-form-item label="描述" name="description">
          <a-textarea v-model:value="formState.description" v-trim :rows="3" placeholder="请输入描述" :maxlength="200" show-count />
        </a-form-item>
      </div>
    </template>
  </modal-form>
</template>

<script setup lang="ts">
  import type { Rule } from 'ant-design-vue/es/form'
  import { reactive, ref, watch } from 'vue'
  import { nextTick } from 'vue'
  import { onUnmounted } from 'vue'

  import ModalForm from '@/components/ModalForm/index.vue'
  import RadioTreeData from '@/components/RadioTreeData/index.vue'
  import { modelLibraryApi } from '@/services/api'

  interface LineExportProps {
    show: boolean
    loading?: boolean
  }

  const props = withDefaults(defineProps<LineExportProps>(), {
    show: false
  })

  const emits = defineEmits<{
    (e: 'update:show', value: boolean): void
    (e: 'submit', formState: any): void
  }>()

  const mainModuleRef = ref()

  const formState = reactive({
    id: '',
    modelBaseId: '',
    name: '',
    value: '',
    versionId: undefined,
    versionInput: '',
    description: ''
  })

  type FormStateType = typeof formState

  const modelFormRules: Record<string, Rule[]> = {
    modelBaseId: [{ required: true, trigger: 'change', message: '请选择模型库' }],
    versionId: [{ required: true, message: '请选择版本号', trigger: 'change' }],
    versionInput: [
      { required: true, message: '请输入版本号名称', trigger: 'change' },
      {
        pattern: /^(?!\.)(\d+\.)*\d+$/,
        message: '仅支持数字和小数点,且以数字结尾'
      }
    ]
  }

  const open = async () => {
    emits('update:show', true)
    await nextTick()
    mainModuleRef.value?.getTreeData()
  }

  const onOk = () => {
    const formData = {
      id: formState.id,
      modelBaseId: formState.modelBaseId,
      versionId: formState.versionId === 'add-version' ? '' : formState.versionId,
      version: formState.versionInput,
      description: formState.description
    }

    emits('submit', formData)
  }

  const onCancel = () => {
    Object.assign(formState, {
      id: '',
      modelBaseId: '',
      name: '',
      value: '',
      versionId: undefined,
      versionInput: '',
      description: ''
    })
    mainModuleRef.value?.clearBread()
    mainModuleRef.value?.setSearchValue()
    emits('update:show', false)
  }

  const stopWatch = watch(
    () => props.show,
    val => {
      if (val) {
        open()
      } else {
        onCancel()
      }
    }
  )

  /* 版本号逻辑--------------------------------------------------------------------------------- */
  interface VersionOption {
    id: string
    version: string
  }
  const versionOption = ref<VersionOption[]>([])

  //已有版本号
  const getVersionList = async (): Promise<void> => {
    const res = await modelLibraryApi.existingVersionNumber({ modelBaseId: formState.modelBaseId })
    versionOption.value = res.data.map((item: VersionOption) => item).concat([{ id: 'add-version', version: '新增版本' }])
  }

  const onRadioTreeChange = () => {
    formState.versionId = undefined
    formState.versionInput = ''
    getVersionList()
  }

  /* 版本号逻辑end--------------------------------------------------------------------------------- */

  onUnmounted(() => {
    stopWatch()
  })

  defineExpose({
    setFormState: (state: Partial<FormStateType>) => {
      Object.assign(formState, state)
    },
    open
  })
</script>

<style lang="less" scoped>
  .from-content {
    overflow-y: auto;
    padding: 0 32px;
    height: 500px;
  }

  .item-to-inline {
    & > .ant-form-item {
      width: 100%;
    }

    .ant-form-item {
      display: inline-block;
      margin-bottom: 20px;
    }
  }
</style>
